from flask import Blueprint,jsonify,request
from db import db1
from utils.comm import *
admin_bp = Blueprint('admin',__name__)


@admin_bp.route('/roles',methods=['POST'])
def roles():
    data = get_data()
    sql =  '''select id from roles where name="%s"'''%(data['name'])
    res = db1.find(sql)
    if not res:
        sql1 = '''insert into roles values(0,'%s')'''%(data['name'])
        db1.update(sql1)
        return jsonify({"code":200,"mes":"添加成功"})
    else:
        return jsonify({"code":10010,"mes":"角色已存在"})

@admin_bp.route('/adminUser',methods=['POST','GET'])
def adminUser():
    if request.method=='GET':
        sql = '''select * from roles'''
        a = db1.fid_all(sql)
        return jsonify({"code":200,"list":a})
    else:
        data = get_data()
        sql = '''insert into admin_user(name,role_id) values('%s','%d')'''%(data['name'],data['role_id'])
        db1.update(sql)
        return jsonify({"code": 200})


@admin_bp.route('/resource',methods=['POST','GET'])
def resource():
    if request.method== 'GET':
        sql = '''select * from resources'''
        a = db1.fid_all(sql)
        return jsonify({"code": 200, "list": a})
    else:
        data = get_data()
        sql = "delete from roles_resource where role_id=%d"%(int(data['id']))
        db1.update(sql)
        for i in data['ids']:
            sql1 = "insert into roles_resource values(%d,%d)" % (int(data['id']),i)
            db1.update(sql1)
        return jsonify({"code":200})











